import { login, logout, getUserInfo, refreshToken } from '@/api/auth'
import { getToken, setToken, removeToken, getRefreshToken, setRefreshToken, removeRefreshToken } from '@/utils/auth'

const state = {
  token: getToken(),
  refreshToken: getRefreshToken(),
  userInfo: null
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_REFRESH_TOKEN: (state, refreshToken) => {
    state.refreshToken = refreshToken
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          const { token, refreshToken, userInfo } = response
          commit('SET_TOKEN', token)
          commit('SET_REFRESH_TOKEN', refreshToken)
          commit('SET_USER_INFO', userInfo)
          setToken(token)
          setRefreshToken(refreshToken)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then(response => {
          const { userInfo } = response
          commit('SET_USER_INFO', userInfo)
          resolve(userInfo)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 刷新Token
  refreshToken({ commit }, refreshToken) {
    return new Promise((resolve, reject) => {
      refreshToken({ refreshToken: refreshToken })
        .then(response => {
          const { token } = response
          commit('SET_TOKEN', token)
          setToken(token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 用户登出
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_REFRESH_TOKEN', '')
          commit('SET_USER_INFO', null)
          removeToken()
          removeRefreshToken()
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 重置Token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_REFRESH_TOKEN', '')
      commit('SET_USER_INFO', null)
      removeToken()
      removeRefreshToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 